/*
 * @features: 功能
 * @description: 说明
 * @Date: 2020-08-27 19:19:43
 * @Author: judu233(769471424@qq.com)
 * @LastEditTime: 2020-08-27 19:33:34
 * @LastEditors: judu233
 */
const { ccclass, property } = cc._decorator;

@ccclass
export default class Bullet_Tracking extends cc.Component {
  @property({
    type: cc.Node,
    displayName: `发射节点`,
    tooltip: `发射位置`
  })
  launch_btn: cc.Node = null;

  @property({
    type: cc.Node,
    displayName: `子弹`
  })
  public bullet: cc.Node = null;

  @property({
    type: cc.Node,
    displayName: `目标`
  })
  public target: cc.Node = null;

  /**开火标志 */
  public fireFlag: boolean = false;

  /**子弹速度 */
  public bulletSpeed = 200;

  onLoad() { this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMoveEvent, this); }

  private touchMoveEvent(evt: cc.Event.EventTouch) {
    if (!this.target) { cc.warn(`目标不存在，请检查!`); return; }
    this.target.x += evt.getDeltaX();
    this.target.y += evt.getDeltaY();
  }

  /**开火 */
  public fire() {
    this.bullet.getComponent(cc.Sprite).enabled = true;
    this.bullet.getChildByName('boom').active = false;
    this.bullet.setPosition(this.launch_btn.position);
    this.bullet.active = true;
    this.fireFlag = true;
  }

  /** 击中目标 */
  public hitTheTarget() {
    this.fireFlag = false;
    this.bullet.getComponent(cc.Sprite).enabled = false;
    this.bullet.getChildByName('boom').active = true;
    this.scheduleOnce(() => {
      this.bullet.getChildByName('boom').active = false;
    }, 0.2);
  }

  update(dt) {
    if (!this.fireFlag) return;

    let targetPos: cc.Vec2 = this.target.getPosition();
    let bulletPos: cc.Vec2 = this.bullet.getPosition();
    let normalizeVec: cc.Vec2 = targetPos.subtract(bulletPos).normalize();

    this.bullet.x += normalizeVec.x * this.bulletSpeed * dt;
    this.bullet.y += normalizeVec.y * this.bulletSpeed * dt;
    // 角度变化以y轴正方向为起点，逆时针角度递增
    this.bullet.angle = cc.v2(0, 1).signAngle(normalizeVec) * 180 / Math.PI;

    //判断是否触碰
    let rect = this.target.getBoundingBox();
    if (rect.contains(bulletPos)) this.hitTheTarget();
  }
}
